﻿using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace ApiHttpClientTest
{
    public static class BlogHelper
    {
        const string Api = "https://localhost:44354/Api/BlogApi5";

        #region HttpClient

        public static async Task<ResponseItem> HttpGetToken(string userName, string password)
        {
            HttpClient client = new HttpClient();
            var retStr = await client.GetStringAsync($"{Api}?username={userName}&password={password}");
            return JsonConvert.DeserializeObject<ResponseItem>(retStr);
        }

        public static async Task<ResponseItem> HttpPost(RequestItem item)
        {
            HttpClient client = new HttpClient();
            
            var jsonStr = JsonConvert.SerializeObject(item);
            var data = Encoding.UTF8.GetBytes(jsonStr);

            var content = new ByteArrayContent(data);
            content.Headers.Add("Content-Type", "application/json");

            var ret = await client.PostAsync(Api, content);
            jsonStr = await ret.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<ResponseItem>(jsonStr);
        }

        #endregion

        #region WebClient

        public static ResponseItem GetToken(string userName, string password)
        {
            WebClient wc = new WebClient();
            var retStr = wc.DownloadString($"{Api}?username={userName}&password={password}");
            return JsonConvert.DeserializeObject<ResponseItem>(retStr);
        }

        public static ResponseItem Post(RequestItem item)
        {
            WebClient wc = new WebClient();
            wc.Headers.Add("Content-Type", "application/json");

            var jsonStr = JsonConvert.SerializeObject(item);
            var data = Encoding.UTF8.GetBytes(jsonStr);

            var ret = wc.UploadData(Api, data);
            jsonStr = Encoding.UTF8.GetString(ret);
            return JsonConvert.DeserializeObject<ResponseItem>(jsonStr);
        }

        #endregion
    }
}
